import logging

from django.db.models import Q
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from rest_framework import viewsets
from rest_framework.decorators import action

from BYD_ERP.utils.base_views import MultipleDestroyMixin, MultipleAuditMixin
from BYD_ERP.utils.pagination import GlobalPagination
from purchase_info.models import PurchaseOrderModel
from purchase_info.serializer.purchase_order_serializer import PurchaseOrderSerializer, PurchaseOrderGetSerializer

logger = logging.getLogger('my')

class PurchaseOrderView(viewsets.ModelViewSet, MultipleDestroyMixin, MultipleAuditMixin):
    """
        create:
        采购订单--新增，注意：其中images_list="1,2,3,4"；里面是附件的ID

        采购订单新增，status：201（成功），return：新增采购订单信息

        destroy:
        采购订单--删除

        采购订单删除，status：204（成功），return：None

        multiple_delete:
        采购订单--批量删除，必传参数：ids=[1,2,3,4,...]

        采购订单批量删除，status：204（成功），return：None

        update:
        采购订单--修改，注意：其中images_list="1,2,3,4"；里面是附件的ID

        采购订单修改，status：200（成功），return：修改后的采购订单信息

        partial_update:
        采购订单--局部修改，可以传任意属性的值，服务器会修改指定的属性值

        采购订单局部修改，status：200（成功），return：修改后的采购订单信息

        list:
        采购订单列表

        采购订单列表信息，status：200（成功），return：采购订单列表

        retrieve:
        根据ID查询某一个采购订单

        查询指定ID的采购订单，status：200（成功），return：指定采购订单

    """
    queryset = PurchaseOrderModel.objects.all()
    serializer_class = PurchaseOrderSerializer
    pagination_class = GlobalPagination

    def get_serializer_class(self):
        if self.action == 'retrieve' or self.action == 'find':
            return PurchaseOrderGetSerializer
        return PurchaseOrderSerializer

    def get_queryset(self):
        if self.action == 'find':  # 过滤查询
            # 获取请求参数（在json中）：
            number_code = self.request.data.get('number_code', None)   # 单据编号
            keyword = self.request.data.get('keyword', None)
            start_date = self.request.data.get('start_date', None)
            end_date = self.request.data.get('end_date', None)
            supplier = self.request.data.get('supplier', 0)
            operator_user = self.request.data.get('operator_user', 0)
            status = self.request.data.get('status', 0)
            remark = self.request.data.get('remark', None)
            query = Q()
            if keyword:
                child_query = Q()
                child_query.add(Q(item_list__name__contains=keyword), 'OR')
                child_query.add(Q(item_list__specification__contains=keyword), 'OR')
                child_query.add(Q(item_list__model_number__contains=keyword), 'OR')
                query.add(child_query, 'AND')
            if start_date:
                query.add(Q(invoices_date__gt=start_date), 'AND')
            if end_date:
                query.add(Q(invoices_date__lt=end_date), 'AND')
            if supplier:
                query.add(Q(supplier__id__contains=supplier), 'AND')
            if operator_user:
                query.add(Q(operator_user=operator_user), 'AND')
            if number_code:
                query.add(Q(number_code__contains=number_code), 'AND')  # 单据编号
            if status:
                query.add(Q(status=status), 'AND')
            if remark:
                query.add(Q(remark__contains=remark), 'AND')

            # distinct()做去重。
            return PurchaseOrderModel.objects.filter(query).distinct().all()
        else:
            return PurchaseOrderModel.objects.all()

    params = openapi.Schema(type=openapi.TYPE_OBJECT, properties={
        'keyword': openapi.Schema(type=openapi.TYPE_STRING, description="名称的关键字或件号、型号"),
        'start_date': openapi.Schema(type=openapi.TYPE_STRING, description="起始日期2024-2-24"),
        'end_date': openapi.Schema(type=openapi.TYPE_STRING, description="结束日期2024-2-24"),
        'status': openapi.Schema(type=openapi.TYPE_STRING, description="状态0或者1,2,3,4,5"),
        'supplier': openapi.Schema(type=openapi.TYPE_INTEGER, description="供应商的ID"),
        'operator_user': openapi.Schema(type=openapi.TYPE_INTEGER, description="制单人/操作用户的ID"),
        'number_code': openapi.Schema(type=openapi.TYPE_STRING, description="单据编号"),
        'remark': openapi.Schema(type=openapi.TYPE_STRING, description="备注/摘要"),
    })

    # 分页参数必须是query_param
    page_param = openapi.Parameter(name='page', in_=openapi.IN_QUERY, description="页号", type=openapi.TYPE_STRING)
    size_param = openapi.Parameter(name='page_size_user_defined', in_=openapi.IN_QUERY, description="每页显示的数量",
                                   type=openapi.TYPE_STRING)

    @swagger_auto_schema(method='post', request_body=params, manual_parameters=[page_param, size_param],
                         operation_description="采购订单的过滤查询")
    # swagger_auto_schema中如果method='get'， 是不能用request_body=open_ids的
    # request_body就是定义json格式的传参
    @action(methods=['post'], detail=False)
    def find(self, request, *args, **kwargs):
        return super(PurchaseOrderView, self).list(request=request, *args, **kwargs)
